#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    查询所有房间
    Add By : cdj <e4ting@qq.com> 2021-07-14 17:57:18
"""
from flask_restful import Resource
from flask         import redirect,request,make_response

# from urllib.parse import urlparse

from e4ting         import util,log
from core.cache     import RoomCache
from models.mysqls  import db,ModelRoom
from core.game.room import Room
import json
import random
# from core.webhook.events import EventBaitPot
# from core.webhook.hooks  import HookSender

class WebListRoom(Resource):
    """ 房间列表 """

    def roominfo(self, uid):
        cache = RoomCache(uid)
        data = cache.get()
        data["players"] = json.loads(data.get("players", "[]") or "[]")
        data["visists"] = json.loads(data.get("visists", "[]") or "[]")
        data["game"]    = json.loads(data.get("game", "{}") or "{}")
        data["players_number"] = len(data["players"])
        data["visists_number"] = len(data["visists"])
        return data

    def get(self, id=None):
        """ 返回房间列表 """
        pngs = ["img/desk1.svg", "img/desk2.svg", "img/desk3.svg", "img/桌布.jpg"]

        data = db.session.query(ModelRoom).filter(ModelRoom.removed==False).all()
        rooms = [[self.roominfo(item.id), item] for item in data]
        items = [
            {
              "imgUrl": random.choice(pngs),
              "route":  "/game",
              "title":     item.name,
              "smallblind": '10',
              "bigblind": '20',
              "shopDesc": '{players_number}名玩家'.format(**info),
              "delivery": '{visists_number}人围观'.format(**info),
              "shopName": '进入房间',
              "tags":[ p["uid"] for p in info["players"][:5] ],
              "uid" : item.id,
            } for info,item in rooms
        ]
        return {
            "code" : 200,
            "data"  : items,
        }
